package com.igeek.shop.web.admin;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.igeek.common.utils.StringUtils;
import com.igeek.shop.entity.Category;
import com.igeek.shop.service.admin.AdminCategoryServiceImpl;


public class AdminCategoryServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private AdminCategoryServiceImpl adminServiceImpl = new AdminCategoryServiceImpl(); 

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String state = request.getParameter("state");
		if(state.equals("queryCategory")) {
			this.queryCategory(request,response);
		}else if(state.equals("addCategory")) {
			this.addCategory(request,response);
		}else if(state.equals("updateCategory")) {
			this.updateCategory(request,response);
		}else if(state.equals("deleteCategory")) {
			this.deleteCategory(request,response);
		}
	}
	
	private void deleteCategory(HttpServletRequest request, HttpServletResponse response) {
		String cid = request.getParameter("cid");
		Category category = new Category(cid,"");
		adminServiceImpl.deleteCategory(category);
		queryCategory(request,response);
	}

	public  void updateCategory(HttpServletRequest request, HttpServletResponse response) {
		String cname = request.getParameter("cname");
		System.out.println(cname);
		String cid = request.getParameter("cid");
		System.out.println(cid);
		Category category = new Category(cid,cname);
		adminServiceImpl.updateCategory(category);
		queryCategory(request,response);
	}

	public void addCategory(HttpServletRequest request, HttpServletResponse response) {
		String cname = request.getParameter("cname");
		String cid = StringUtils.getUUID();
		Category category = new Category(cid,cname);
		adminServiceImpl.addCategory(category);
		queryCategory(request,response);
	}

	public  void  queryCategory(HttpServletRequest request, HttpServletResponse response) {
		List<Category> categoryList = adminServiceImpl.queryCategory();
		request.setAttribute("categoryList", categoryList);
		try {
			request.getRequestDispatcher("/admin/category/list.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
